{% from 'IcsocUIBundle:Macro:actions.html.twig' import button %}

<div class="widget-main">
    <!-- #section:elements.tab.option -->
    <div class="tabbable">
        <ul class="nav nav-tabs" id="myTab-report">
            {% for item, itemValue in reportItems %}
                <li {% if loop.first == true %} } class="active" {% endif %}>
                    <a data-toggle="tab" href="#tab-content-report-{{ item }}" data-text="{{ item }}" >{{ item|trans() }}</a>
                </li>
            {% endfor %}
        </ul>

        <div class="tab-content" id="tab-content-report">
            {% for item, itemValue in reportItems %}
            <div id="tab-content-report-{{ item }}" {% if loop.first == true %} class="tab-pane in active" {% else %} class="tab-pane in" {% endif %}">
            {% for key, itemVal in itemValue %}
            <div class="widget-box widget-color-blue3">
                <!-- #section:custom/widget-box.options.collapsed -->
                <div class="widget-header widget-header-small">
                    <h6 class="widget-title">
                        <i class="ace-icon fa fa-sort"></i>
                        {{ key|trans() }}
                    </h6>

                    <div class="widget-toolbar">
                        {% if key == 'custom_report' %}
                            <a href="#" data-action="settings">
                                <i class="ace-icon fa fa-plus add-custom-item"> {{ 'Add Custom Items'|trans }} </i>
                            </a>
                        {% else %}
                            <a href="#" data-action="settings">
                                <i class="ace-icon fa fa-plus add-fixed-item"> {{ 'Add Custom Items'|trans }} </i>
                            </a>
                        {% endif %}
                        <a href="#" data-action="settings">
                            <i class="ace-icon fa fa-check-square">{{ 'Check All'|trans() }}</i>
                        </a>
                        <a href="#" data-action="settings">
                            <i class="ace-icon fa fa-square">{{ 'Check None'|trans() }}</i>
                        </a>
                    </div>
                </div>

                <!-- /section:custom/widget-box.options.collapsed -->
                <div class="widget-body">
                    <div class="row widget-main" id="widget-main-{{ key }}">
                        {% for k, itemV in itemVal %}
                            <div class="col-lg-3 col-sm-3 col-xs-3">
                                <label>
                                    <input class="ace item" type="checkbox" data-id="{{ k }}" id="{{ item }}{{ key }}{{ k }}" value="{{ k }}" data="item" data-type="{{ item }}" data-text="{{ key }}" {% if itemV.checked is defined and itemV.checked == true %}checked{% endif %} />
                                    {% if itemV.showValue is defined %}
                                        <span class="lbl" title="{% if itemV.text is defined %} {{ itemV.text|trans }} {% else %}{{ itemV.showValue }} {% endif %}" id="{{ item }}{{ key|replace({'_report' : ''}) }}{{ k }}"> {{ itemV.showValue }}</span>
                                    {% else %}
                                        <span class="lbl" title="{{ itemV.text|trans }}" id="{{ item }}{{ key|replace({'_report' : ''}) }}{{ k }}"> {{ itemV.text|trans }}</span>
                                    {% endif %}
                                    {% if itemV.sort is defined and itemV.sort is not empty %}
                                        <input type="hidden" id="{{ item }}{{ key|replace({'_report' : ''}) }}{{ k }}-sort" name="sort" value="{{ itemV.sort }}" />
                                        <input type="text" value="{{ itemV.sort }}" disabled style="width:31px;height:15px;padding:0 2px;text-align:center" />
                                    {% else %}
                                        <input type="hidden" id="{{ item }}{{ key|replace({'_report' : ''}) }}{{ k }}-sort" name="sort" value="100" />
                                        <input type="text" value="100" disabled style="width:31px;height:15px;padding:0 2px;text-align:center" />
                                    {% endif %}
                                    {% if itemV.globalConfig is defined and itemV.globalConfig == 1 %}
                                        <input type="hidden" id="{{ item }}{{ key|replace({'_report' : ''}) }}{{ k }}-globalConfig" name="globalConfig" value="1">
                                    {% else %}
                                        <input type="hidden" id="{{ item }}{{ key|replace({'_report' : ''}) }}{{ k }}-globalConfig" name="globalConfig" value="0">
                                    {% endif %}
                                    {% if itemV.text is defined %}
                                        <input type="hidden" name="defaultValue" id="{{ item }}{{ key|replace({'_report' : ''}) }}{{ k }}-defaultValue" value="{{ itemV.text|trans }}" />
                                    {% else %}
                                        <input type="hidden" name="defaultValue" id="{{ item }}{{ key|replace({'_report' : ''}) }}{{ k }}-defaultValue" value="" />
                                    {% endif %}
                                    {% if itemV.showValue is defined %}
                                        <input type="hidden" name="originItemName" id="{{ item }}{{ key|replace({'_report' : ''}) }}{{ k }}-originItemName" value="{{ itemV.showValue }}" />
                                    {% else %}
                                        <input type="hidden" name="originItemName" id="{{ item }}{{ key|replace({'_report' : ''}) }}{{ k }}-originItemName" value="{{ itemV.text|trans }}" />
                                    {% endif %}
                                    <input type="hidden" name="originItemSort" id="{{ item }}{{ key|replace({'_report' : ''}) }}{{ k }}-originItemSort" value="{% if itemV.sort is defined and itemV.sort is not empty %} {{ itemV.sort }} {% else %} 100 {% endif %} ">
                                </label>
                                {% if itemV.calculate is defined and itemV.calculate == true %}
                                    <a href="javascript:" title="{{ 'Setting calculation'|trans }}">
                                        <i class="ace-icon fa fa-edit"></i>
                                    </a>
                                {% elseif itemV.normalCalculate is defined and itemV.normalCalculate == 1 %}
                                    <a href="javascript:" title="{{ 'Setting calculation'|trans }}">
                                        <i class="ace-icon fa fa-edit"></i>
                                    </a>
                                {% endif %}
                                {% if itemV.custom is defined and itemV.custom == true %}
                                    <a href="javascript:" title="{{ 'Delete'|trans }}" class="popover-error" data-rel="popover" data-placement="left" data-content="">
                                        <i class="ace-icon fa fa-trash-o"></i>
                                    </a>
                                {% endif %}
                            </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
        {% endfor %}
    </div>
</div>

<!-- #section:指标计算项配置 -->
<div id="dialog-message-report" class="hide">
    <div class="widget-main">
        <div class="row">
            <div class="control-group" style="margin-left: 10px">
                <span>
                    {{ 'Item Name'|trans }}：<input type="text" id="itemName" maxlength="10"><span id="itemMessage" style="color: red"></span>
                </span>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <span class="defaultValue" style="color: green">{{ "Item Default Value"|trans }}:&nbsp;&nbsp;<span id="defaultValue"></span></span>
                <br/><br/>
                <span>
                    {{ 'Item Sort'|trans }}：<input type="text" id="itemSort" maxlength="10" />
                    <span id="sortMessage" style="color: red"></span>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <span id="sortdesc" style="color: green">{{ 'The range of item sort for 1-100 group priority'|trans }}</span>
                </span>
                <br/><br/>
                <label class="isGlobalConfig">
                    <input id="isGlobal" type="checkbox" class="ace" value="1"/>
                    <span class="lbl">{{ 'Apply to global configurations'|trans }}</span>
                    <span style="color: green;margin-left: 105px;">{{ "Your modification will apply to all the roles if checked"|trans }}</span>
                </label>
            </div>
        </div>
        <div class="row" style="margin: -5px 10px 0px 10px" id="numerator-toolbar">
            <h5 class="header green"> {{ 'numerator'|trans }} <a href="#" data-action="collapse"><i class="ace-icon fa fa-plus"></i></a></h5>
        </div>
        <div class="row" id="numerator-control"></div>
        <div class="row" style="margin-top: 10px;margin-left: 10px" id="denominator-toolbar">
            <h5 class="header green">
                {{ 'denominator'|trans }}
                <a href="#" data-action="collapse">
                    <i class="ace-icon fa fa-plus"></i>
                </a>
                <label>
                    <input id="percent" type="checkbox" class="ace" />
                    <span class="lbl"> {{ 'Calculated Percent'|trans }} </span>
                </label>
            </h5>
        </div>
        <div class="row" id="denominator-control"></div>
    </div>
</div>
<!-- /section:指标计算项配置 -->


<div class="widget-toolbox padding-8 clearfix">
    {{ button('Save Config', 'save-report-config', 'fa-save', 'btn-info') }}
</div>

<script type="text/javascript">
    /** 报表指标配置 */
    var reportItmes = {"system":{"fixed":[], "custom":[]},"queue":{"fixed":[], "custom":[]},"agent":{"fixed":[], "custom":[]},"group":{"fixed":[], "custom":[]}};
    /** 全局报表配置 */
    var globalReportItmes = {"system":{"fixed":[], "custom":[]},"queue":{"fixed":[], "custom":[]},"agent":{"fixed":[], "custom":[]},"group":{"fixed":[], "custom":[]}};
    var items = {{ items|raw }};
    var originItems = {{ originItems|raw }};
    /** 需要计算的指标 */
    var calculateItems = {{ calculateItems|raw }};
    /** 自定义指标 **/
    var customItems = {"system":{"fixed":{},"custom":{}},"queue":{"fixed":{},"custom":{}},"agent":{"fixed":{},"custom":{}},"group":{"fixed":{},"custom":{}}};
    {% for key, customItemChild in customItems %}
    {% for k, customItem in customItemChild %}
    {% for k1,v1 in customItem %}
    customItems["{{ key }}"]["{{ k }}"]["{{ k1 }}"] = "{{ v1 }}";
    {% endfor %}
    {% endfor %}
    {% endfor %}
    /** 当前选中的报表 */
    var currentReport = 'system';
    /** 当前编辑的指标 */
    var currentItem = null;
    var currentItemType = 'fixed';

    var numeratorEditunable = ['inboundConnInXSecsRate', 'inboundAbandonInXSecsRate', 'inboundConnInXSecsNum', 'inboundAbandonInXSecsNum'];
    var currentCustomItemType = 'fixed';
    var showValues = {"system":{"fixed":{},"custom":{}},"queue":{"fixed":{},"custom":{}},"agent":{"fixed":{},"custom":{}},"group":{"fixed":{},"custom":{}}};
    var globalShowValues = {"system":{"fixed":{},"custom":{}},"queue":{"fixed":{},"custom":{}},"agent":{"fixed":{},"custom":{}},"group":{"fixed":{},"custom":{}}};
    $(document).ready(function(){
        /** Tab切换,设置当前Tab */
        $('#myTab-report a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            currentReport = $(e.target).attr('data-text');
        });

        /** 保存配置 */
        $('#save-report-config').on('click', function() {
            if (click_id=="") {
                $.gritter.add({
                    title: '{{ 'Prompt'|trans }}',
                    text: '{{ 'You did not select any role cannot perform this operation'|trans }}!',
                    class_name: 'gritter-error'
                });

                return false;
            }

            $(this).attr('disabled', true);

            reportItmes = {"system":{"fixed":[], "custom":[]},"queue":{"fixed":[], "custom":[]},"agent":{"fixed":[], "custom":[]},"group":{"fixed":[], "custom":[]}};

            $('#tab-content-report input[type=checkbox][data=item]:checked').each(function() {
                var data_type = $(this).attr('data-type');
                var data_text = $(this).attr('data-text').replace('_report', '');
                if (typeof data_type != 'undefined' && typeof data_text != 'undefined') {

                    reportItmes[data_type][data_text].push($(this).val());
                }
            });

            $('#tab-content-report input[type=checkbox]').each(function() {
                var currentVal = $(this).val();
                var data_type = $(this).attr('data-type');
                var data_text = $(this).attr('data-text').replace('_report', '');
                var dataId = $(this).attr('data-id');
                var showVal = $.trim($('#'+data_type+data_text+dataId).text());
                var sort = $.trim($('#'+data_type+data_text+dataId+"-sort").val());
                var globalConfig = $('#'+data_type+data_text+dataId+"-globalConfig").val();

                showValues[data_type][data_text][currentVal] = {"name":showVal, "sort":sort, "globalConfig":globalConfig};
                var globalShowItemName = showVal;
                var globalShowItemSort = sort;
                if (globalConfig == 0) {
                    var originItemValue = $.trim($('#'+data_type+data_text+currentVal+'-originItemName').val());
                    var originItemSort = $.trim($('#'+data_type+data_text+currentVal+'-originItemSort').val());
                    globalShowItemName = originItemValue;
                    globalShowItemSort = originItemSort;
                }
                globalShowValues[data_type][data_text][currentVal] = {"name":globalShowItemName, "sort":globalShowItemSort, "globalConfig":globalConfig};
                if (typeof data_type != 'undefined' && typeof data_text != 'undefined') {

                    globalReportItmes[data_type][data_text].push($(this).val());
                }
            });
            var reportConfig = {"reportItmes":reportItmes,"calculateItems":calculateItems,"customItems":customItems,"showValues":showValues};
            var globalreportConfig = {"reportItmes":globalReportItmes,"calculateItems":calculateItems,"customItems":customItems,"showValues":globalShowValues};


            $.ajax({
                url: '{{ path("icsoc_security_role_report_config") }}',
                dataType: 'json',
                type: 'post',
                data: {reportConfig: JSON.stringify(reportConfig), roleId:click_id, globalReprotConfig: JSON.stringify(globalreportConfig)},
                success: function (response) {
                    $("#save-report-config").attr('disabled', false);
                    if (response.code != 200) {
                        $.gritter.add({
                            title: '{{ 'Prompt'|trans }}',
                            text: response.message,
                            class_name: 'gritter-error'
                        });
                    } else {
                        $.gritter.add({
                            title: '{{ 'Prompt'|trans }}',
                            text: '{{ 'Add success'|trans }}',
                            class_name: 'gritter-success'
                        });
                    }
                }
            });
        });

        /** 全选 */
        $('#tab-content-report .fa-check-square').on('click', function () {
            var $element = $(this).closest('.widget-box').find('.widget-main');
            $element.find('input[type=checkbox]').prop('checked', true);
        });

        /** 全不选 */
        $('#tab-content-report .fa-square').on('click', function () {
            var $element = $(this).closest('.widget-box').find('.widget-main');
            $element.find('input[type=checkbox]').prop('checked', false);
        });

        /** 添加自定义指标、编辑指标计算项 */
        $('#tab-content-report').on('click', '.add-custom-item,.fa-edit,.add-fixed-item', function() {
            /** 判断是否有选中的角色 */
            if (click_id=="") {
                $.gritter.add({
                    title: '{{ 'Prompt'|trans }}',
                    text: '{{ 'You did not select any role cannot perform this operation'|trans }}!',
                    class_name: 'gritter-error'
                });

                return false;
            }

            var topL0 = $("#dialog-message-report").offset().top;
            $(document).scrollTop(topL0+'px');

            /** 清空之前的设置 */
            $('#numerator-control').empty();
            $('#denominator-control').empty();
            $('#itemMessage').html('');
            $('#sortMessage').html('');
            $('#defaultValue').html('');
            $('#percent').prop("checked", false);
            $("#numerator-toolbar").find("a").removeClass("hide");
            $('#isGlobal').prop("checked", false);

            if ($(this).hasClass('fa-edit')) {
                //$('#itemName').val($(this).parent().parent().find('.lbl').html()).attr('disabled', true);
                $('#itemName').val($.trim($(this).parent().parent().find('.lbl').html()));
                $('#itemSort').val($(this).parent().parent().find('input[type=hidden][name=sort]').val());
                $('#defaultValue').html($(this).parent().parent().find('input[type=hidden][name=defaultValue]').val());

                var add_custom_item = false;
                currentItemType = $(this).parent().parent().find('input[type=checkbox]').attr('data-text').replace('_report', '');
                currentItem = $(this).parent().parent().find('input[type=checkbox]').val();
                $('#'+currentReport+currentItemType+currentItem+'-originItemName').val($.trim($(this).parent().parent().find('.lbl').html()));
                $('#'+currentReport+currentItemType+currentItem+'-originItemSort').val($.trim($(this).parent().parent().find('input[type=hidden][name=sort]').val()));
                if (typeof calculateItems[currentReport][currentItem] != 'undefined' && typeof calculateItems[currentReport][currentItem]['percent'] != 'undefined' && calculateItems[currentReport][currentItem]['percent'] == true) {
                    $('#percent').prop("checked", true);
                } else {
                    $('#percent').prop("checked", false);
                }

                if ($.inArray(currentItem, numeratorEditunable) != -1) {
                    $("#numerator-toolbar").find("a").addClass("hide");
                } else {
                    $("#numerator-toolbar").find("a").removeClass("hide");
                }

                /** 设置isGlobal的默认值*/
                if ($('#'+currentReport+currentItemType+currentItem+'-globalConfig').val() == 1) {
                    $('#isGlobal').prop('checked', true);
                } else {
                    $('#isGlobal').prop('checked', false);
                }

                /*if ($(this).parent().next().children().hasClass('fa-trash-o')) {
                 currentItemType = 'custom';
                 } else {
                 currentItemType = 'fixed';
                 }*/
                currentCustomItemType = 'fixed';
            } else if($(this).hasClass('add-fixed-item')) {
                var add_custom_item = true;
                currentItemType = 'fixed';
                currentCustomItemType = 'fixed';
                $('#itemName').val('').attr('disabled', false);
                $('#itemSort').val('');
                /** 动态添加指标元素的位置 */
                var $element = $(this).closest('.widget-box').find('.widget-main');
                //自定义字段字段标识
                currentItem = getRandomString(currentReport+"{{ time }}");
            } else {
                var add_custom_item = true;
                currentItemType = 'custom';
                currentCustomItemType = 'custom';
                $('#itemName').val('').attr('disabled', false);
                $('#itemSort').val('');
                /** 动态添加指标元素的位置 */
                var $element = $(this).closest('.widget-box').find('.widget-main');
                //自定义字段字段标识
                currentItem = getRandomString(currentReport+"{{ time }}");
            }

            $('.isGlobalConfig').show();

            if ( (add_custom_item == false && $('#defaultValue').html() == '') || add_custom_item == true) {
                $('.defaultValue').hide();
            } else {
                $('.defaultValue').show();
            }

            /** 设置Options */
            if (add_custom_item == false && typeof originItems[currentReport][currentItemType][currentItem]['normalCalculate'] != 'undefined' &&
                    originItems[currentReport][currentItemType][currentItem]['normalCalculate'] == 1) {
                $('#numerator-control').hide();
                $('#denominator-control').hide();
                $('#numerator-toolbar').hide();
                $('#denominator-toolbar').hide();
                var checkMolecules = false;
            } else {
                $('#numerator-control').show();
                $('#denominator-control').show();
                $('#numerator-toolbar').show();
                $('#denominator-toolbar').show();
                var checkMolecules = true;

                if (add_custom_item == false && typeof calculateItems[currentReport][currentItem]['numerator'] != 'undefined') {
                    var $control = $('#numerator-control');
                    $.each(calculateItems[currentReport][currentItem]['numerator'], function(index, data){
                        if (index == 'multiply') {
                            var tmpArr = [];
                            $.each(data, function (logic, value) {
                                if (typeof value == 'object') {
                                    $.each(value, function(id,item) {
                                        tmpArr.push(item);
                                    });
                                }
                            });
                            $.each(tmpArr, function(id, itemStr){
                                var arr = itemStr.split('*');
                                var node = arr[0];
                                var trueValue = arr[1];
                                //当计算的配置中出现数字时，则为自定义数值的情况
                                if($.isNumeric(trueValue)) {
                                    var customNumberValue = trueValue;
                                    trueValue = 'customNumber';
                                }
                                if (node == 'firstMultiplyItem') { //node为1时，为第一个指标项为乘法的情况
                                    var nodeController = $('#numerator-control');
                                    generateCalculateOptions(nodeController, trueValue, 'multiply', 1, customNumberValue);
                                } else {
                                    var nodeController = $('#numerator-control').find(".item option[value='"+node+"'][selected]").parent().parent();
                                    generateCalculateOptions(nodeController, trueValue, 'multiply', '', customNumberValue);
                                }
                            });
                        } else {
                            if (typeof data == 'object') {
                                $.each(data, function(ind, d){
                                    if($.isNumeric(d)) {
                                        var customNumberValue = d;
                                        d = 'customNumber';
                                    }
                                    generateCalculateOptions($control, d, index, '', customNumberValue);
                                });
                            }
                        }
                    });
                }

                if (add_custom_item == false && typeof calculateItems[currentReport][currentItem]['denominator'] != 'undefined') {
                    var $control = $('#denominator-control');
                    $.each(calculateItems[currentReport][currentItem]['denominator'], function(index, data){
                        if (index == 'multiply') {
                            var tmpArr = [];
                            $.each(data, function (logic, value) {
                                if (typeof value == 'object') {
                                    $.each(value, function(id,item) {
                                        tmpArr.push(item);
                                    });
                                }
                            });
                            $.each(tmpArr, function(id, itemStr){
                                var arr = itemStr.split('*');
                                var node = arr[0];
                                var trueValue = arr[1];
                                //当计算的配置中出现数字时，则为自定义数值的情况
                                if($.isNumeric(trueValue)) {
                                    var customNumberValue = trueValue;
                                    trueValue = 'customNumber';
                                }
                                if (node == 'firstMultiplyItem') { //node为1时，为第一个指标项为乘法的情况
                                    var nodeController = $('#denominator-control');
                                    generateCalculateOptions(nodeController, trueValue, 'multiply', 1, customNumberValue);
                                } else {
                                    var nodeController = $('#denominator-control').find(".item option[value='"+node+"'][selected]").parent().parent();
                                    generateCalculateOptions(nodeController, trueValue, 'multiply', '', customNumberValue);
                                }
                            });
                        } else {
                            if (typeof data == 'object') {
                                $.each(data, function(ind, d){
                                    //当计算的配置中出现数字时，则为自定义数值的情况
                                    if($.isNumeric(d)) {
                                        var customNumberValue = d;
                                        d = 'customNumber';
                                    }
                                    generateCalculateOptions($control, d, index, '', customNumberValue);
                                });
                            }
                        }

                    });
                }
                addCustomNumberText();
            }

            var dialog = $( "#dialog-message-report" ).removeClass('hide').dialog({
                modal: true,
                title: "{{ 'Itmes Config'|trans }}",
                title_html: true,
                width:600,
                closeOnEscape:false,
                open:function(event,ui){$(".ui-dialog-titlebar-close").hide();},
                buttons: [
                    {
                        text: "{{ 'Cancel'|trans}}",
                        "class" : "btn btn-xs",
                        click: function() {
                            $( this ).dialog( "close" );
                            $( this ).dialog( "destroy" );
                            $( this ).addClass('hide');
                        }
                    },
                    {
                        text: "{{ 'OK'|trans}}",
                        "class" : "btn btn-primary btn-xs",
                        click: function() {
                            $("#dialog-message-report").find('select').removeAttr("disabled");

                            var customItemName = $.trim($('#itemName').val());
                            if (customItemName == '') {
                                $('#itemMessage').html("{{ 'Item Name cannot be empty'|trans }}");
                                return;
                            }

                            var isCustomNumber = 0;
                            $('.number-text').each(function() {
                                if (isNaN($(this).val()) || $(this).val() == '') {
                                    isCustomNumber = 1;
                                }
                            });
                            //验证输入的自定义数值是否是数字
                            if (isCustomNumber == 1) {
                                $.gritter.add({
                                    title: '{{ 'Prompt'|trans }}',
                                    text: '{{ 'Custom number must be number'|trans }}!',
                                    class_name: 'gritter-error'
                                });
                                return;
                            }

                            if(isNaN($('#itemSort').val())){
                                $('#sortMessage').html("{{ 'Item Sort must be number'|trans }}");
                                return;
                            } else {
                                var isEmpty = /^\s*$/;
                                if (isEmpty.test($('#itemSort').val()) == true) {
                                    $('#sortMessage').html("{{ 'Item Sort cannot be empty'|trans }}");
                                    return;
                                } else {
                                    var ex = /^\d+$/;
                                    if (ex.test($('#itemSort').val()) == false) {
                                        $('#sortMessage').html("{{ 'Item Sort must be integer'|trans }}");
                                        return;
                                    }
                                    if ($('#itemSort').val() < 1 || $('#itemSort').val() >100) {
                                        $('#sortMessage').html("{{ 'Item Sort must be 1-100'|trans }}");
                                        return;
                                    }
                                }
                            }

                            /** 是否保存到全局配置中*/
                            if ($('#isGlobal').prop('checked') == true) {
                                $('#'+currentReport+currentItemType+currentItem+'-globalConfig').val(1);
                                var isglobal = 1;
                            } else {
                                $('#'+currentReport+currentItemType+currentItem+'-globalConfig').val(0);
                                var isglobal = 0;
                            }

                            $('#'+currentReport+currentItemType+currentItem).html(customItemName);
                            $('#'+currentReport+currentItemType+currentItem+'-sort').val($('#itemSort').val());
                            $('#'+currentReport+currentItemType+currentItem+'-sort').next().removeAttr('disabled');
                            $('#'+currentReport+currentItemType+currentItem+'-sort').next().val($('#itemSort').val());
                            $('#'+currentReport+currentItemType+currentItem+'-sort').next().attr('disabled', 'disabled');
                            var sort = $('#itemSort').val();

                            var $items = {"numerator":{"plus":[],"minus":[],"multiply":{"plus":[],"minus":[]}},
                                          "denominator":{"plus":[],"minus":[],"multiply":{"plus":[],"minus":[]}},
                                          "percent":0};
                            var number = 0;
                            /** 分子计算规则 */
                            $('#numerator-control').children('.control-group').each(function(index) {
                                var logic = $(this).find('.logic').val();
                                var value = $(this).find('.item').val();
                                //当选择的分子是customnumber时，则为自定义数值的情况，直接把数值存入计算公式中
                                if (value == 'customNumber') {
                                    value = $(this).find('.number-text').val();
                                }
                                if (typeof value != 'undefined' && value != '') {
                                    number++;
                                    if (logic == 'minus') {
                                        $items.numerator.minus.push(value);
                                    } else if (logic == 'multiply') {
                                        var lastIndex = index-1;
                                        if (lastIndex == -1) {
                                            var lastNextItem = 'firstMultiplyItem';
                                            $items.numerator.multiply.plus.push(lastNextItem+'*'+value);
                                        } else {
                                            var lastNextItem = $('#numerator-control').children('.control-group').eq(lastIndex).find('.item').val();
                                            var lastLogic = $('#numerator-control').children('.control-group').eq(lastIndex).find('.logic').val();
                                            if (lastLogic == 'plus' || lastLogic == 'multiply') {
                                                $items.numerator.multiply.plus.push(lastNextItem+'*'+value);
                                            } else {
                                                $items.numerator.multiply.minus.push(lastNextItem+'*'+value);
                                            }
                                        }
                                    } else {
                                        $items.numerator.plus.push(value);
                                    }
                                }
                            });

                            if (number == 0 && checkMolecules == true) {
                                $('#itemMessage').html("{{ 'Molecules can not be empty'|trans }}");
                                return;
                            }

                            /** 分母计算规则 */
                            $('#denominator-control').children('.control-group').each(function(index) {
                                var logic = $(this).find('.logic').val();
                                var value = $(this).find('.item').val();
                                if (value == 'customNumber') {
                                    value = $(this).find('.number-text').val();
                                }

                                if (typeof value != 'undefined' && value != '') {
                                    if (logic == 'minus') {
                                        $items.denominator.minus.push(value);
                                    } else if (logic == 'multiply') {
                                        var lastIndex = index-1;
                                        if (lastIndex == -1) {
                                            var lastNextItem = 'firstMultiplyItem';
                                            $items.denominator.multiply.plus.push(lastNextItem+'*'+value);
                                        } else {
                                            var lastNextItem = $('#denominator-control').children('.control-group').eq(lastIndex).find('.item').val();
                                            var lastLogic = $('#denominator-control').children('.control-group').eq(lastIndex).find('.logic').val();
                                            if (lastLogic == 'plus' || lastLogic == 'multiply') {
                                                $items.denominator.multiply.plus.push(lastNextItem+'*'+value);
                                            } else {
                                                $items.denominator.multiply.minus.push(lastNextItem+'*'+value);
                                            }
                                        }
                                    } else {
                                        $items.denominator.plus.push(value);
                                    }
                                }
                            });
                            /** 是否计算百分比 */
                            $items.percent = $('#percent').prop( "checked" );

                            /** 页面中添加自定义指标元素 */
                            if (add_custom_item == true) {
                                //var currentItemId = currentReport+'custom_report'+currentItem;
                                var currentItemId = currentReport+currentCustomItemType+'_report'+currentItem;
                                generateCustomItem($element, currentItemId, currentReport, currentItem, customItemName,currentItemType,sort,isglobal);
                                /** 保存自定义指标信息 */
                                customItems[currentReport][currentItemType][currentItem] = customItemName;
                                items[currentReport][currentItemType][currentItem] = customItemName;
                                originItems[currentReport][currentItemType][currentItem] = customItemName;
                            }

                            /** 保存指标计算项信息 */
                            calculateItems[currentReport][currentItem] = $items;
                            $( this ).dialog( "close" );
                            $( this ).dialog( "destroy" );
                            $( this ).addClass('hide');
                        }
                    }
                ]
            });
        });

        /** 添加指标计算项 */
        $('#dialog-message-report .fa-plus').on('click', function(){
            var $control = $(this).parent().parent().parent().next();

            if ($control.children().length > 5) {
                alert("{{ 'Can Not continue to add'|trans }}");
                return false;
            }

            generateCalculateOptions($control);
            addCustomNumberText();
        });

        /** 删除指标计算项 */
        $('#dialog-message-report').on('click', '.fa-times', function(){
            $(this).parent().parent().remove();
        });

        /** 删除动态添加的指标 */
        $('#tab-content-report').on('click', '.fa-trash-o', function() {
            /** 判断该指标是否被用于计算，否则不能被删除 */
            currentItem = $(this).parent().parent().find('input[type=checkbox]').val();
            var if_delete = true;

            $.each(calculateItems[currentReport], function(index, data){
                $.each(data, function(i, obj){
                    if (typeof obj == 'object') {
                        $.each(obj, function(i, d){
                            if ($.inArray(currentItem, d ) != -1 ) {
                                if_delete = index;
                                return false;
                            }
                        });
                    }
                });
            });

            if (if_delete != true) {
                $('[data-rel=popover]').popover({html:true});
                $(this).parent().attr('data-content', items[currentReport][currentItemType][if_delete]+'指标中计算项中包含该指标,不能删除');
                //$(this).trigger("click");
                return false;
            }
            var itemType = $(this).parent().parent().find('input[type=checkbox]').attr('data-text').replace('_report', '');
            delete customItems[currentReport][itemType][currentItem];
            delete calculateItems[currentReport][currentItem];
            $(this).parent().parent().remove();
        });
    });

    /**
     * 生成指标计算项
     */
    function generateCalculateOptions($control, value, logic, special, customNumberValue) {
        /** 计算指标选择项 */
        var options = '<option value="">{{ "Please select a Item"|trans }}</option>';

        var editunable = '';
        var hide = '';
        if ($.inArray(currentItem, numeratorEditunable) != -1 && $.inArray(value, numeratorEditunable) != -1) {
            editunable = 'disabled';
            hide = 'hide';
        }

        var isSelected = '';
        var width = '170px';
        var str = '';
        $.each(items[currentReport][currentItemType], function(index, data) {
            if (currentItem == index) {
                return true;
            }
            if ($.inArray(index, numeratorEditunable) != -1 && editunable != 'disabled') {
                return true;
            }

            var showVal = $.trim($('#'+currentReport+currentItemType+index).html());
            if (value == index) {
                options += '<option value="'+index+'" selected>'+showVal+'</option>';
            } else {
                options += '<option value="'+index+'">'+showVal+'</option>';
            }
        });
        //当为自定义数值时，设置选中并添加自定义数值文本框及调整宽度
        if (value == 'customNumber') {
            isSelected = 'selected';
            width = '110px';
            str = '<input type="text" class="number-text" name="number-text" value="'+customNumberValue+'" style="width:56px;height:30px;margin-left:4px" />';
        }
        //自定义数值
        options += '<option value="customNumber" '+isSelected+'>{{ "customNumber"|trans }}</option>';

        var logicPlus = (logic == 'plus') ? 'selected' : '';
        var logicMinus = (logic == 'minus') ? 'selected' : '';
        var logicMultiply = (logic == 'multiply') ? 'selected' : '';
        var content = '<div class="control-group col-xs-12 col-sm-6" style="margin-top: 5px">\
                           <select '+editunable+' class="logic">\
                                <option value="plus" '+logicPlus+'>+</option>\
                                <option value="minus" '+logicMinus+'>-</option>\
                                <option value="multiply" '+logicMultiply+'>*</option>\
                           </select>\
                           <select class="item" '+editunable+' style="width: '+width+'">'+options+'</select>'+str+'\
                           <a href="#" data-action="close" class="'+hide+'">\
                               <i class="ace-icon fa fa-times"></i>\
                           </a>\
                       </div>';

        if (logic == 'multiply') {
            if(special == 1) {
                $control.prepend(content);
            } else {
                $control.after(content);
            }
        } else {
            $control.append(content);
        }
    }

    /**
     * 动态生成自定义指标
     * @param $control
     * @param currentItemId
     * @param currentReport
     * @param currentItem
     * @param customItemName
     */
    function generateCustomItem($control, currentItemId, currentReport, currentItem, customItemName, currentCustomItemType, sort, isglobal)
    {
        var itemContent = '<div class="col-lg-2 col-sm-3 col-xs-6">\
                               <label>\
                                   <input type="checkbox" checked id="'+currentItemId+'" value="'+currentItem+'" data-id="'+currentItem+'" data-text="'+currentCustomItemType+'" data-type="'+currentReport+'" data="item" class="ace" value="'+customItemName+'"/>\
                                   <span class="lbl" title="'+customItemName+'" id="'+currentReport+currentCustomItemType+currentItem+'">'+customItemName+'</span>\
                                   <input type="hidden" id="'+currentReport+currentCustomItemType+currentItem+'-sort" name="sort" value="'+sort+'" />\
                                   <input type="text" value="'+sort+'" disabled style="width:31px;height:15px;padding:0 2px;text-align:center" />\
                                   <input type="hidden" id="'+currentReport+currentCustomItemType+currentItem+'-globalConfig" name="globalConfig" value="'+isglobal+'">\
                                   <input type="hidden" name="originItemName" id="'+currentReport+currentCustomItemType+currentItem+'-originItemName" value="'+customItemName+'" />\
                                   <input type="hidden" name="originItemSort" id="'+currentReport+currentCustomItemType+currentItem+'-originItemSort" value="'+sort+'" />\
                               </label>\
                               <a href="#" title="{{ 'Setting calculation'|trans }}">\
                                    <i class="ace-icon fa fa-edit"></i>\
                               </a>\
                               <a href="#" title="{{ 'Delete'|trans }}">\
                                    <i class="ace-icon fa fa-trash-o"></i>\
                               </a>\
                           </div>'
        $control.append(itemContent);
    }

    /**
     * 添加固定数值的文本框
     */
    function addCustomNumberText()
    {
        $('.item').on('change', function() {
            if ($(this).val() == 'customNumber') {
                $(this).parent().find('.number-text').remove();
                $(this).css('width', '110px');
                $(this).after('<input type="text" class="number-text" name="number-text" style="width:56px;height:30px;margin-left:4px" />');
            } else {
                $(this).parent().find('.number-text').remove();
                $(this).css('width', '170px');
            }
        });
    }
</script>
